package com.itheima52.mobilesafe.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密
 * 
 * @author ludaxu
 * 
 */
public class MD5Utils {
	public static String encode(String password) {

		StringBuffer sb = new StringBuffer();
		try {
			MessageDigest instance = MessageDigest.getInstance("MD5");// 获取MD5算法对象
			byte[] digest = instance.digest(password.getBytes());// 对字符串加密,返回的字节数组
			for (byte b : digest) {
				int i = b & 0xff;// 获取字节的低八位
				String hexString = Integer.toHexString(i);// 将整数转化为16进制数
				// System.out.println(hexString);
				if (hexString.length() < 2) {
					hexString = "0" + hexString;// 如果是1位的话,补0

				}
				sb.append(hexString);

			}
			// System.out.println("md5:" + sb.toString());
			// System.out.println("md5 length:" + sb.toString().length());// MD5
			// 都是32位

		} catch (NoSuchAlgorithmException e) {
			// 没有该算法时,抛出异常,MD5一定有,所以不会走这里
			e.printStackTrace();
		}

		return sb.toString();
	}

}
